package bd.com.escenic.flexilunch.util;

/**
 * $URL: http://flexilunch.googlecode.com/svn/trunk/core/src/main/java/bd/com/escenic/flexilunch/util/HibernateUtil.java $
 * $Id: HibernateUtil.java 16 2009-06-09 04:07:50Z shihab.uddin@gmail.com $
 * $Date: 2009-06-09 04:07:50 +0000 (Tue, 09 Jun 2009) $
 * $Author: shihab.uddin@gmail.com $
 * $Revision: 16 $
 */

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * $Id: HibernateUtil.java 16 2009-06-09 04:07:50Z shihab.uddin@gmail.com $.
 *
 * @author <a href="mailto:shihab.uddin@gmail.com">Shihab Uddin</a>
 * @version $Revision: 16 $
 */
public class HibernateUtil {
  protected static final Logger mLogger = Logger.getLogger(HibernateUtil.class);

  private static final SessionFactory SESSION_FACTORY;

  static {
    try {
      Configuration configuration = new Configuration();
      SESSION_FACTORY = configuration.configure().buildSessionFactory();
    }
    catch (Throwable e) {
      mLogger.fatal("Initial SessionFactory creation failed.", e);
      throw new ExceptionInInitializerError(e);
    }
  }

  private HibernateUtil() {
  }

  public static void beginTransaction() {
    Session session = SESSION_FACTORY.getCurrentSession();
    session.beginTransaction();
  }

  public static <T> T execute(final Transaction<T> pTransaction)
      throws HibernateException {
    Session session = SESSION_FACTORY.getCurrentSession();
    return pTransaction.execute(session);
  }

  public static void commitTransaction() {
    Session session = SESSION_FACTORY.getCurrentSession();
    session.getTransaction().commit();
  }

  public static void rollbackTransaction() {
    Session session = SESSION_FACTORY.getCurrentSession();
    session.getTransaction().rollback();
  }

  public static interface Transaction<T> {
    public T execute(final Session pSession) throws HibernateException;
  }
}
